<template>
  <div>
    <div class="margin-container-list">
      <div class="pad-b-20 pad-t-20">
        <el-button type="primary" @click="handleAddOrEdit(0)">添加编码</el-button>
        <el-button type="primary" @click="handleImport()">导入编码</el-button>
        <el-button @click="handleBatchDelete()">批量删除</el-button>
      </div>
      <div class="top-operate-default">
        <div class="search-item">
          <el-select v-model="dataListQuery.keywordType">
            <el-option label="编码" value='1'></el-option>
            <el-option label="名称" value='2'></el-option>
          </el-select>
          <el-input @keyup.enter.native="handleSearch" v-model="dataListQuery.keyword" placeholder="请输入内容"
            style="width: 220px;"></el-input>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 内容列表 -->
      <div class="table-container mar-t-20">
        <el-table ref="multipleTable" :data="dataList" v-loading="listLoading" element-loading-text="加载中"
          style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column width="55px" type="selection"></el-table-column>
          <el-table-column label="编码" prop="code" align="center"></el-table-column>
          <el-table-column label="名称" prop="title" align="center"></el-table-column>
          <el-table-column label="关税税率" prop="tariffRate" align="center">
            <template slot-scope="scope">
              {{scope.row.tariffRate}}%
            </template>
          </el-table-column>
          <el-table-column label="增值税税率" prop="valueAddedTaxRate" align="center">
            <template slot-scope="scope">
              {{scope.row.valueAddedTaxRate}}%
            </template>
          </el-table-column>
          <el-table-column label="消费税税率" prop="consumptionTaxRate" align="center">
            <template slot-scope="scope">
              {{scope.row.consumptionTaxRate}}%
            </template>
          </el-table-column>
          <el-table-column label="综合税税率" prop="comprehensiveTaxRate" align="center">
            <template slot-scope="scope">
              {{scope.row.comprehensiveTaxRate}}%
            </template>
          </el-table-column>
          <el-table-column width="140px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="handleAddOrEdit(scope.row.codeId)">编辑</el-button>
              <el-button type="text" @click="handleBatchDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <pagination v-show="total>0" :total="total" :page.sync="dataListQuery.currentPage"
        :limit.sync="dataListQuery.size" @pagination="initData" />
    </div>
    <!--新增-->
    <el-dialog :title="title" :visible.sync="entityVisible" width="650px">
      <div v-loading="editLoading" element-loading-text="加载中">
        <el-form ref="form" :model="entity" :rules="rules" label-position="right" label-width="100px"
          class="mar-l-20 mar-r-30">
          <el-form-item label="编码" prop="code">
            <el-input v-model="entity.code" maxlength="32" placeholder="请输入编码"></el-input>
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="entity.title" maxlength="50" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item label="关税税率" prop="tariffRate">
            <el-input v-model="entity.tariffRate" maxlength="5" placeholder="请输入关税税率,1-100"><template
                slot="append">%</template></el-input>
          </el-form-item>
          <el-form-item label="增值税税率" prop="valueAddedTaxRate">
            <el-input v-model="entity.valueAddedTaxRate" maxlength="5" placeholder="请输入增值税税率,1-100"><template
                slot="append">%</template></el-input>
          </el-form-item>
          <el-form-item label="消费税税率" prop="consumptionTaxRate">
            <el-input v-model="entity.consumptionTaxRate" maxlength="5" placeholder="请输入消费税税率,1-100"><template
                slot="append">%</template></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveEntity" :disabled="editLoading">确认</el-button>
          <el-button @click="handleCancelSaveEntity">取消</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 批量导入弹窗 -->
    <el-dialog width="700px" v-el-drag-dialog title="导入海关商品编码" :visible.sync="batchImportCustomsGoodsCodeVisible">
      <div v-loading="importLoading" element-loading-text="导入中...">
        <el-form ref="importForm" :model="importEntity" label-position="right" label-width="100px"
          style='width: 500px; margin-left:50px;'>
          <el-form-item label="导入文件" prop="fileUrl">
            <div v-if="importEntity.fileName">{{importEntity.fileName}}</div>
            <el-upload class="upload-demo" ref="importCustomsCode" name="files" accept=".xlsx, .xls"
              action="/api/common/uploadFiles" :multiple="false" :show-file-list="false" :data="token"
              :before-upload="beforeUploadFile" :on-success="handleUploadSuccess">
              <el-button size="small" type="primary">选取文件</el-button>
            </el-upload>
            <span class="font-blue">
              <el-button @click="downloadCustomsGoodsCodeTemplate" type="text">下载导入模板</el-button>
            </span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="importCustomsGoodsCode">确定</el-button>
          <el-button @click="batchImportCustomsGoodsCodeVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>

</style>

<script>
  import elDragDialog from '@/directive/el-dragDialog'
  import {
    pageCustomsGoodsCode,
    getDetail,
    save,
    deleteByBatch
  } from '@/api/goods/customsGoodsCode'
  import {
    downloadFile
  } from '@/api/common/common'
  import {
    getToken
  } from '@/utils/auth'
  export default {
    directives: {
      elDragDialog
    },
    data() {
      const validateNum = (rule, value, callback) => {
        const flag = this.checkInputNum(value)
        if (!flag) {
          callback(new Error('请输入数字'))
          return
        }
        if (value < 0 || value > 100) {
          callback(new Error('请输入大于0并且小于100的数字'))
          return
        }
        callback()
      }
      return {
        token: '',
        total: 0,
        dataList: [],
        listLoading: false,
        multipleSelection: [],
        dataListQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: this.getEnterpriseId(),
          keywordType: '1',
          keyword: ''
        },
        title: '添加海关商品编码',
        editLoading: false,
        entity: {
          code: '',
          title: '',
          tariffRate: '',
          valueAddedTaxRate: '',
          consumptionTaxRate: ''
        },
        batchImportCustomsGoodsCodeVisible: false,
        importLoading: false,
        // 导入海关商品编码实体
        importEntity: {
          fileName: '',
          fileUrl: ''
        },
        entityVisible: false,
        rules: {
          code: [{
            required: true,
            message: '请填写编码!',
            trigger: 'blur'
          }],
          tariffRate: [{
            required: true,
            message: '请填写关税率!',
            trigger: 'blur'
          }, {
            validator: validateNum,
            trigger: 'blur'
          }],
          valueAddedTaxRate: [{
            required: true,
            message: '请填写增值税率!',
            trigger: 'blur'
          }, {
            validator: validateNum,
            trigger: 'blur'
          }],
          consumptionTaxRate: [{
            required: true,
            message: '请填写消费税率!',
            trigger: 'blur'
          }, {
            validator: validateNum,
            trigger: 'blur'
          }]
        }
      }
    },
    // 初始化页面
    created() {
      this.token = {
        accessToken: getToken()
      }
      this.initData()
    },
    filters: {

    },
    mounted() {},
    methods: {
      initData() {
        this.listLoading = true
        pageCustomsGoodsCode(this.dataListQuery).then(response => {
          if (response.isError) return
          this.total = response.data.total
          this.dataList = response.data.records
          this.listLoading = false
        })
      },
      handleReset() {
        this.dataListQuery.keywordType = '1'
        this.dataListQuery.keyword = ''
        this.initData()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 查询
      handleSearch() {
        this.dataListQuery.currentPage = 1
        this.initData()
      },
      handleBatchDelete(row) {
        console.log(row)
        var codeIds = []
        if (row && row.codeId) {
          codeIds.push(row.codeId)
        } else {
          if (this.multipleSelection.length > 0) {
            this.multipleSelection.forEach((item) => {
              codeIds.push(item.codeId)
            })
          }
        }
        if (codeIds.length <= 0) {
          this.msgError('请选择要删除的数据!')
          return
        }
        this.$confirm('确定要删除数据吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 批量删除
          if (codeIds.length > 1) {
            const params = {
              enterpriseId: this.getEnterpriseId(),
              codeIds: codeIds
            }
            this.$bus.$emit('asyncHandle', '300101', params, () => {
              this.initData()
            })
          } else {
            deleteByBatch(this.getEnterpriseId(), codeIds).then(response => {
              if (response.isError) return
              this.msgSuccess('删除成功')
              this.initData()
            })
          }
        }).catch(() => {})
      },
      // 添加或编辑
      handleAddOrEdit(codeId) {
        this.entity = {}
        this.entityVisible = true
        this.editLoading = false
        this.title = '添加海关商品编码'
        if (codeId && codeId > 0) {
          this.title = '编辑海关商品编码'
          this.editLoading = true
          getDetail(codeId).then(response => {
            this.editLoading = false
            if (response.isError) return
            this.entity = response.data
          })
        }
      },
      saveEntity() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.entity.enterpriseId = this.getEnterpriseId()
            save(this.entity).then(response => {
              if (response.isError) return
              this.msgSuccess('保存成功')
              this.initData()
              this.entityVisible = false
            })
          }
        })
      },
      handleCancelSaveEntity() {
        this.$refs['form'].clearValidate()
        this.entityVisible = false
      },
      handleImport() {
        this.batchImportCustomsGoodsCodeVisible = true
      },
      downloadCustomsGoodsCodeTemplate() {
        var options = {}
        var fileName = '导入海关商品编码模板.xlsx'
        downloadFile('/goods/enterpriseCustomsGoodsCode/downloadImportCustomsGoodsCodeTemplate', options, fileName)
      },
      // 批量导入海关商品编码
      importCustomsGoodsCode() {
        if (!this.importEntity.fileUrl) {
          this.msgError('请上传导入文件')
          return
        }
        const params = {
          enterpriseId: this.getEnterpriseId(),
          fileUrl: this.importEntity.fileUrl
        }
        this.$bus.$emit('asyncHandle', '300102', params, () => {
          this.importEntity.fileName = ''
          this.batchImportCustomsGoodsCodeVisible = false
          this.initData()
        })
      },
      beforeUploadFile(file) {
        const ext = file.name.substring(file.name.lastIndexOf('.') + 1)
        if (ext !== 'xlsx' && ext !== 'xls') {
          this.msgError('请上传xls或xlsx格式的Excel文件')
          return false
        }
        return true
      },
      handleUploadSuccess(res, file) {
        if (res.code !== 101) {
          this.importEntity.fileName = ''
          this.msgError(res.msg)
          return
        }
        this.importEntity.fileName = file.name
        this.importEntity.fileUrl = res.data[0]
        this.msgSuccess('文件已上传')
      }
    }
  }
</script>
